import React from 'react';
import './Upload.scss';
import { ImageUploader, ImageUploadItem, Toast } from 'antd-mobile';
import { UploadResponse } from '@/API/commonAPI';
import { upload } from '@/store/modules/consultStore';
import { useEnhanceDispatch } from '@/hooks';

interface UploadProps {
  fileList: ImageUploadItem[];
  setFileList: (uploads: ImageUploadItem[]) => void;
}

const Upload: React.FunctionComponent<UploadProps> = ({ fileList, setFileList }) => {
  const enhanceDispatch = useEnhanceDispatch();

  const beforeUpload = (file: File) => {
    if (file.size > 1024 * 1024) {
      Toast.show('请选择小于 1M 的图片');
      return null;
    }
    return file;
  };

  const onChangeFieList = (uploads: ImageUploadItem[]) => {
    setFileList(uploads);
  };

  const onUpload = async (file: File) => {
    const formData = new FormData();
    formData.append('file', file);
    const uploadResponse: UploadResponse = await enhanceDispatch(upload(formData)).unwrap();
    return uploadResponse;
  };

  return (
    <ImageUploader maxCount={3} value={fileList} onChange={onChangeFieList} upload={onUpload} beforeUpload={beforeUpload}></ImageUploader>
  );
};

export default Upload;